<template>
  <div class="out">
    <zHeader pageTitle="周边配套"></zHeader>

    <!-- <div style="height: 10px;"></div> -->
    <!-- <section class="tableOut" v-if="ifShowTable">
      <vantTable
        :columns="zhouBianPeiTaoColumns"
        :data="zhouBianPeiTaoData.zhouBianPeiTaoList"
        :height="300"
      ></vantTable>
    </section> -->

    <div class="pageOut">
      <div id="mapShow"></div>
      <div id="panel"></div>
      <div class="btnArea">
        <div class="btnItem" :class="{ 'active': selectedBtnIndex == 0 }" @click="btnItemClickHandler('教育', 0)">教育</div>
        <div class="btnItem" :class="{ 'active': selectedBtnIndex == 1 }" @click="btnItemClickHandler('交通', 1)">交通</div>
        <div class="btnItem" :class="{ 'active': selectedBtnIndex == 2 }" @click="btnItemClickHandler('医疗', 2)">医疗</div>
        <div class="btnItem" :class="{ 'active': selectedBtnIndex == 3 }" @click="btnItemClickHandler('生活', 3)">生活</div>
        <div class="btnItem" :class="{ 'active': selectedBtnIndex == 4 }" @click="btnItemClickHandler('休闲', 4)">休闲</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader'
import { useRouter } from 'vue-router'
const router = useRouter()
import vantTable from 'vant-table'
import { postZhouBianPeiTaoList, postZhouBianDingWeiList } from '@/api/zhoubianpeitao/index.js'
import { postXiaoQuDetail } from '@/api/xiaoqu/index.js'
import { pageConstant } from '@/config/contant.js'
import { getSelectedXiaoQuId } from '@/config/config.js'

if (!getSelectedXiaoQuId()) {
  showDialog({
    message: '暂无小区数据，请先配置小区',
  }).then(() => {
    router.back()
  })
}

/**
 * 获取周边配置数据
 */
const zhouBianPeiTaoColumns = ref([
  {
    prop: 'peiTaoName',
    title: '名称',
    width: '108px',
  },
  {
    prop: 'typeName',
    title: '类型',
    width: '60px',
  },
  {
    prop: 'weiZhi',
    title: '位置',
    width: '130px',
  },
  {
    prop: 'juLi',
    title: '距离',
    width: '60px',
  },
])
const zhouBianPeiTaoData = ref({})
const ifShowTable = ref(true)
let xiaoQuCityCode = null
let xiaoQuName = ''
const loadZhouBianPeiTaoDataHandler = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });

  postZhouBianPeiTaoList({xiaoQuId: getSelectedXiaoQuId()}).then(res => {
    // 关闭加载中提示
    closeToast();

    if (res.data.code == pageConstant.okCode) {
      zhouBianPeiTaoData.value = res.data.data

      if (zhouBianPeiTaoData.value.zhouBianPeiTaoList && zhouBianPeiTaoData.value.zhouBianPeiTaoList.length > 0) {
        zhouBianPeiTaoData.value.zhouBianPeiTaoList.forEach(item => {
          item.juLi = item.juLi + 'km'
        })
      } else {
        ifShowTable.value = false
      }

      window._AMapSecurityConfig = {
        securityJsCode: zhouBianPeiTaoData.value.gaoDeMiYao,
      };

      handleZhouBianPeiTaoData()

      initMap()
    } else {
      showToast(res.data.msg);
    }
  })
  .catch((err) => {
    console.log(err)
  })
}
const handleZhouBianPeiTaoData = () => {
  if (!zhouBianPeiTaoData.value.jingDu || !zhouBianPeiTaoData.value.jingDu) {
    showDialog({
      message: '暂无小区经纬度数据',
    }).then(() => {
      router.back()
    })
  }

  if (!zhouBianPeiTaoData.value.bianJu) {
    showDialog({
      message: '暂无查询边距数据',
    }).then(() => {
      router.back()
    })
  }
}
const loadXiaoQuDetailDataHandler = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });

  postXiaoQuDetail({xiaoQuId: getSelectedXiaoQuId()}).then(res => {
    // 关闭加载中提示
    closeToast();

    if (res.data.code == pageConstant.okCode) {
      handleXiaoQuCityCode(res)
    } else {
      showToast(res.data.msg);
    }
  })
  .catch((err) => {
    console.log(err)
  })
}
const handleXiaoQuCityCode = (res) => {
  if (res.data.data.xiaoQuWeiZhiMa) {
    xiaoQuCityCode = res.data.data.xiaoQuWeiZhiMa
    xiaoQuName = res.data.data.xiaoQuName
    createXiaoQuMarkerHandler()
  } else {
    showDialog({
      message: '暂无小区城市数据',
    }).then(() => {
      router.back()
    })
  }
}
let otherMarkList = [
  {
    name: '郭公庄站',
    jingDu: '116.301889',
    weiDu: '39.814322'
  }
]
const loadZhouBianDingWeiDataHandler = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });

  postZhouBianDingWeiList({xiaoQuId: getSelectedXiaoQuId()}).then(res => {
    // 关闭加载中提示
    closeToast();

    if (res.data.code == pageConstant.okCode) {
      otherMarkList = res.data.data.map(item => {
        return {
          name: item.zhouBianDingWeiName,
          jingDu: item.jingDu,
          weiDu: item.weiDu
        }
      })
    } else {
      showToast(res.data.msg);
    }
  })
  .catch((err) => {
    console.log(err)
  })
}
onMounted(() => {
  loadZhouBianPeiTaoDataHandler()
  loadZhouBianDingWeiDataHandler()
})

/**
 * 地图初始化
 */
let map = null;
let searchContent = ''
let amap = null
// 图标中间空心不好看
let otherSvg = `
  <svg viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><style>.cls-1{fill:#00bae6;}.cls-2 { fill: #ffffff;}</style></defs><title/><g id="icons"><g data-name="Layer 3" id="Layer_3"><path class="cls-1" d="M18.72,8.31a10.79,10.79,0,0,0-5.17,5.24A12.74,12.74,0,0,0,14.7,26.81l9.93,14.25,9.92-14.25A12.33,12.33,0,0,0,37,19.36C37,10.6,28,4,18.72,8.31Zm6.08,15.2A4.51,4.51,0,1,1,29.3,19,4.51,4.51,0,0,1,24.8,23.51Z"/><circle class="cls-2" cx="24.8" cy="19" r="4.51"/></g></g></svg>
`
const initMap = () => {
  AMapLoader.load({
    key: zhouBianPeiTaoData.value.gaoDeKey, //此处填入我们注册账号后获取的Key
    version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch'], //需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    amap = AMap
    map = new AMap.Map("mapShow", { //设置地图容器id
      viewMode: "3D", //是否为3D地图模式
      zoom: 15, //初始化地图级别
      center: [zhouBianPeiTaoData.value.jingDu, zhouBianPeiTaoData.value.weiDu], //初始化地图中心点位置
      resizeEnable: true
    });

    for(let i = 0; i < otherMarkList.length; i++) {
      createOtherMarkerHandler(otherMarkList[i])
    }
    loadXiaoQuDetailDataHandler()

    // 正式用的时候打开，这个每天100次有些不耐用，现在按钮点击时可以正常调用的
    amapPlaceSearchHandler('教育')
  }).catch(e => {
    console.log(e);
  })
}

/**
 * 创建小区mark点
 */
const createXiaoQuMarkerHandler = () => {
  new amap.Marker({
    position: [zhouBianPeiTaoData.value.jingDu, zhouBianPeiTaoData.value.weiDu],
    map: map
  });
  new amap.Text({
    text: xiaoQuName,
    anchor: 'top-center', // 设置文本标记锚点
    offset: [0, -82],
    style:{
      'padding': '.75rem 1rem',
      'border-radius': '.25rem',
      'background-color': '#1684fc',
      'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
      'text-align': 'center',
      'font-size': '16px',
      'color': 'white'
    },
    position: [zhouBianPeiTaoData.value.jingDu, zhouBianPeiTaoData.value.weiDu],
    map: map
  })
}

/**
 * 指定点mark显示
 */
const createOtherMarkerHandler = (markerData) => {
  let icon = new amap.Icon({
    image: 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(otherSvg))),
    size: new amap.Size(36, 36),
    imageSize: new amap.Size(36, 36),
    anchor: 'center'
  })
  new amap.Marker({
    position: [markerData.jingDu, markerData.weiDu],
    offset: [-18, -31],
    icon: icon,
    map: map
  })

  new amap.Text({
    text: markerData.name,
    anchor: 'top-center', // 设置文本标记锚点
    offset: [0, -75],
    style:{
      'padding': '.75rem 1rem',
      'border-radius': '.25rem',
      // 'background-color': '#00cfff',
      // 'background-color': '#00afd6',
      'background-color': '#00bae6',
      'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
      'text-align': 'center',
      'font-size': '16px',
      'color': 'white'
    },
    position: [markerData.jingDu, markerData.weiDu],
    map: map
  })
}

/**
 * 类型按钮功能
 */
const selectedBtnIndex = ref(0)
const btnItemClickHandler = (searchContent, index) => {
  amapPlaceSearchHandler(searchContent)

  selectedBtnIndex.value = index
}

/**
 * 地图关键词搜索功能
 */
let existedMarkersList = []
let placeSearch = null
const amapPlaceSearchHandler = (searchContent) => {
  amap.plugin(["AMap.PlaceSearch"], function() {
    // 清空上一次的地址查询结果
    if (placeSearch) {
      placeSearch.clear();
    }

    // 构造地点查询类
    placeSearch = new amap.PlaceSearch({
        type: searchContent, // 兴趣点类别
        pageSize: 3, // 单页显示结果条数
        pageIndex: 1, // 页码
        city: xiaoQuCityCode, // 兴趣点城市
        citylimit: true,  //是否强制限制在设置的城市内搜索
        map: map, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
    });

    var cpoint = [zhouBianPeiTaoData.value.jingDu, zhouBianPeiTaoData.value.weiDu]; //中心点坐标
    placeSearch.searchNearBy('', cpoint, zhouBianPeiTaoData.value.bianJu, function(status, result) {
      // 清空上一次的文本标记
      existedMarkersList.forEach(marker => {
        marker.setMap(null)
      });

      result.poiList.pois.forEach(item => {
        // 创建纯文本标记
        let marker = new amap.Text({
          text: item.name,
          anchor:'top-center', // 设置文本标记锚点
          offset: [0, -80],
          style:{
            'padding': '.75rem 1rem',
            'border-radius': '.25rem',
            'background-color': 'white',
            'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
            'text-align': 'center',
            'font-size': '14px',
            'color': 'blue'
          },
          position: [item.location.lng, item.location.lat],
          map: map
        })

        existedMarkersList.push(marker)
      })
    });
  });
}
</script>

<style lang="scss" scoped>
.out {
  min-height: 100dvh;
  width: 100vw;
  
  .tableOut {
    padding: 10px 20px;
    padding-bottom: 0;

    ::v-deep .vant-table-wrapper {
      border: 1px solid #ebedf0;
      border-bottom: 0;
    }
  }

  .pageOut {
    width: 100%;
    min-height: 520px;
    padding: 20px;
    padding-top: 10px;
    position: relative;
    box-sizing: border-box;

    #mapShow {
      width: 100%;
      height: 520px;
      // margin: 100px auto;
      // border: 1px solid red;
      // box-shadow: 0 2px 10px 0 rgba(14, 33, 39, .2);
      // border-radius: 4px;
    }
    #panel {
      // position: absolute;
      background-color: white;
      max-height: 90%;
      overflow-y: auto;
      // bottom: 10px;
      // right: 30px;
      width: 100%;

      ::v-deep .poi-name {
        max-width: 100%;
      }
    }

    .btnArea {
      display: flex;
      border: 1px solid rgb(22, 132, 252);
      border-right: 0px;
      border-radius: 2px;
      position: absolute;
      top: 485px;
      left: calc(50vw - 152px);
      // left: calc(50vw - 130px);

      .btnItem {
        height: 30px;
        width: 60px;
        border-right: 1px solid #1684fc;
        background-color: #fff;
        color: rgb(22, 132, 252);
        line-height: 30px;
        text-align: center;
        font-weight: 500;
      }

      .active {
        background-color: rgb(22, 132, 252);
        color: #fff;
      }
    }
  }
}
</style>